import Request from './request.js'
import { modal, toast } from './extendApi.js'
import { getStorage, removeStorage, clearStorage } from './storage.js'
import { env } from './env.js'

// 不同的实例有不同的配置，如：图片实例，文件实例....
const instance = new Request({
	baseURL: env.baseURL,
	timeout: 6000
})

//  通过实例配置拦截器，会覆盖上面的默认拦截器
instance.interceptors.request = (config) => {
	let token = getStorage('token')
	if (token) {
		config.header['token'] = token
	}

	return config
}

instance.interceptors.response = async (response) => {
	let { isSuccess, data } = response
	if (!isSuccess) {
		uni.showToast({
			title: "网络异常请重试",
			icon: "none"
		})
		return response
	}

	// 判断服务器响应的业务状态码
	switch (data.code) {
		case 200:
			return data;

			// token失效
		case 208:
			const res = await modal({
				content: '鉴权失败,请重新登录',
				showCancel: false
			})
			// 用户点击了确定
			if (res) {
				clearStorage()
				uni.navigateTo({
					url: '/pages/login/login'
				})
			}
			return response

		default:
			toast({
				title: '程序出现异常，请联系客服或稍后重试'
			})
			return Promise.reject(response)
	}

}

export default instance